<template>
    <div class="chole">
        <div class="search">
            <el-form :inline="true" :model="query" class="demo-form-inline">
                <el-form-item>
                    <el-input v-model="query.key" placeholder="家系名、姓名、身份证号" clearable style="width: 240px;" />
                </el-form-item>
                <el-form-item>
                    <el-button color="#b9e8e3" plain class="btn" @click="getSearch">查询</el-button>
                    <el-button color="#17b3a3" class="btn2" @click="getAdd">新增</el-button>
                    <el-button color="#17b3a3" class="btn2" @click="getExport">导出EXCEL</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="table">
            <el-table ref="singleTableRef" :data="tableData" highlight-current-row style="width: 100%" border>
                <el-table-column property="sampleCode" label="样本编码" width="150" />
                <el-table-column property="idCard" label="身份证号" width="150" />
                <el-table-column property="name" label="姓名" width="80" />
                <el-table-column property="sex" label="性别" width="80">
                    <template #default="scope">
                        <span v-if="scope.row.sex == 1">男</span>
                        <span v-if="scope.row.sex == 2">女</span>
                    </template>
                </el-table-column>
                <el-table-column property="age" label="年龄" width="80" />
                <el-table-column property="telephone" label="电话" width="150" />
                <el-table-column property="birthday" label="生日" width="150" />
                <el-table-column property="email" label="邮箱" width="180" />
                <el-table-column property="nation" label="民族" width="100" />
                <el-table-column property="comeFrom" label="居住地" width="260" />
                <el-table-column property="homeAddress" label="家庭住址" width="260" />
                <el-table-column property="familyName" label="家系名称" width="120" />
                <el-table-column property="createOn" label="创建时间" width="150" />
                <el-table-column property="createBy" label="创建人" width="80" />
                <el-table-column property="modifiedOn" label="修改时间" width="150" />
                <el-table-column property="modifiedBy" label="修改人" width="80" />
                <el-table-column property="remark" label="备注" width="50" />
                <el-table-column label="操作" width="100" fixed="right">
                    <template #default="scope">
                        <el-button text @click="getUpdate(scope.row.id)">修改</el-button>
                        <el-button text @click="getDelete(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <el-dialog v-model="dialogVisible" :title="title" width="800">
            <el-form ref="ruleFormRef" style="padding:30px 10px 10px" :model="ruleForm" :rules="rules"
                label-width="auto">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="身份证号" prop="idCard">
                            <el-input v-model="ruleForm.idCard" @blur="handleBlur" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="姓名" prop="name">
                            <el-input v-model="ruleForm.name" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item label="家系" prop="count">
                            <el-select v-model="ruleForm.familyId" placeholder="家系">
                                <el-option v-for="item in options" :key="item.value"
                                    :label="`${item.name}(${item.sourceIdCard})`" :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="性别">
                            <el-radio-group v-model="ruleForm.sex">
                                <el-radio label="1" size="large">男</el-radio>
                                <el-radio label="2" size="large">女</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="年龄">
                            <el-input-number v-model="ruleForm.age" :min="0" :max="100" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="电话">
                            <el-input v-model="ruleForm.telephone" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="生日">
                            <el-date-picker v-model="ruleForm.birthday" type="date" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="邮箱">
                            <el-input v-model="ruleForm.email" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="民族">
                            <el-input v-model="ruleForm.nation" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="居住地">
                    <el-input v-model="ruleForm.comeFrom" />
                </el-form-item>
                <el-form-item label="家庭住址">
                    <el-input v-model="ruleForm.homeAddress" />
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="ruleForm.remark" type="textarea" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <page :query="query" :total="total" @size-change="sChange" @page-change="pChange"></page>
    </div>
</template>

<script lang="ts" setup>

import { nextTick, onMounted, reactive, ref } from 'vue';
import { ComponentSize, ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import page from '@/components/page.vue'
import { donorsinfoCard, donorsinfoDelete, donorsinfoExport, donorsinfoList, donorsinfoSave, donorsinfoShow, donorsinfoUpdate,donorsinfoAllList } from '@/api/donorsinfo';


const query = reactive({
    t: Date.now(),
    page: 1,
    limit: 10,
    key: ''
})
const tableData = ref([])
const currentRow = ref()
const total = ref(0)
const dialogVisible = ref(false)
// 表单
const title = ref('')
interface RuleForm {
    name: string
    idCard: string
    familyId: number | null
    sex: number
    age: number | null
    remark: string
    telephone: string
    birthday: string
    email: string
    nation: string
    comeFrom: string
    homeAddress: string
}
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    idCard: '',
    name: '',
    familyId: null,
    sex: 1,
    age: 0,
    telephone: '',
    birthday: '',
    email: '',
    nation: '',
    comeFrom: '',
    homeAddress: '',
    remark: ''

})
const options = ref([])

const rules = reactive<FormRules<RuleForm>>({
    name: [
        { required: true, message: '名称不能为空', trigger: 'blur' },
    ],
    idCard: [
        {
            required: true,
            message: '身份证号不能为空',
            trigger: 'blur',
        },
        {
            pattern: /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/,
            message: '请输入有效的身份证',
            trigger: 'blur'
        }
    ]
})
const familyId = ref()
const size = ref<ComponentSize>('default')
const disabled = ref(false)

// 函数：=========================================
// 生命周期
onMounted(() => {
    getDonorsinfo()
})
// 渲染表格数据
function getDonorsinfo() {
    donorsinfoList(query).then(res => {
        console.log(res, '888');
        tableData.value = res.page.list
        total.value = res.page.totalCount
    })
}
// 查询
function getSearch() {
    query.page = 1
    getDonorsinfo()
}
// 分页
// 切换条数
const sChange = (val: number) => {
    console.log(`切换为每页：${val}条`);
    query.limit = val
    getDonorsinfo()
}
// 切换页数
const pChange = (val: number) => {
    console.log(`第${val}页`);
    query.page = val
    getDonorsinfo()
}
// 新增
function getAdd() {
    dialogVisible.value = true
    title.value = '新增'
    // 重置表单
    nextTick(() => {
        ruleFormRef.value.resetFields()
    })
    donorsinfoAllList().then(res => {
        console.log(res);
        options.value = res.AllList
    })
}
// 导出
function getExport() {
    const key = query.key ? query.key : ''
    // console.log(`query.key 的值是: ${key}`);
    donorsinfoExport(key).then(res => {
        // console.log(res, 'jiuj');
        // 创建一个二进制对象  用来存储Excel文件数据
        let blob = new Blob([res])
        // 利用a标签的下载功能
        const link = document.createElement('a')
        // 创建一个下载链接，并将其赋值给href
        link.href = window.URL.createObjectURL(blob)
        link.target = "_blank"
        // 设置文件名
        let nowTime = new Date()
        link.setAttribute('download', `样本来源_${nowTime.getTime()}.xlsx`)
        // 将a标签添加到页面上
        document.body.appendChild(link)
        // 手动触发点击事件
        link.click()
        // 移除a标签
        document.body.removeChild(link)
    }).catch(err => {
        console.error('导出失败:', err);
        ElMessage.error('导出失败');
    })
}
//编辑
function getUpdate(val: number) {
    dialogVisible.value = true
    title.value = '修改'
    donorsinfoAllList().then(res => {
        console.log(res);
        options.value = res.AllList
    })
    donorsinfoShow(val).then(res => {
        // console.log(res, '99');
        ruleForm.name = res.donorsInfo.name
        ruleForm.idCard = res.donorsInfo.idCard
        ruleForm.familyId = res.donorsInfo.familyId
        ruleForm.remark = res.donorsInfo.remark
        ruleForm.sex = res.donorsInfo.sex
        ruleForm.age = res.donorsInfo.age
        ruleForm.telephone = res.donorsInfo.telephone
        ruleForm.birthday = res.donorsInfo.birthday
        ruleForm.email = res.donorsInfo.email
        ruleForm.nation = res.donorsInfo.nation
        ruleForm.comeFrom = res.donorsInfo.comeFrom
        ruleForm.homeAddress = res.donorsInfo.homeAddress
    })
}
// 表单-确定
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (title.value == '新增') {
                donorsinfoSave(ruleForm).then(res => {
                    // console.log(res, '88');
                    ElMessage.success('添加成功')
                    dialogVisible.value = false
                    getDonorsinfo()
                })
                    .catch(err => {
                        ElMessage.error('添加失败')
                    })
            } else if (title.value == '修改') {
                donorsinfoUpdate(ruleForm).then(res => {
                    // console.log(res, '5');
                    ElMessage.success('修改成功')
                    dialogVisible.value = false
                    getDonorsinfo()
                })
                    .catch(err => {
                        ElMessage.error('添加失败')
                    })
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}
// 取消
const resetForm = (formEl: FormInstance | undefined) => {
    dialogVisible.value = false

    if (!formEl) return
    formEl.resetFields()
}

// 身份证
function handleBlur() {
    // console.log(111);
    donorsinfoCard(ruleForm.idCard).then(res => {
        // console.log(res);
    })
}

// 删除
function getDelete(val: any) {
    const id = [val]
    ElMessageBox.confirm(
        `确定对[id=${val}]进行[删除]操作？`,
        'Warning',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        donorsinfoDelete(id).then(res => {
            ElMessage.success('删除成功')
            getDonorsinfo()
        })
    })

}

</script>

<style lang="scss" scoped>
.chole {
    .search {
        .btn {
            color: #5d5c5c;
        }

        .btn2 {
            color: #fff;
        }

    }

    :deep .table {
        .el-table thead th {
            background-color: #fff !important;
            color: #909399;
        }

        .cell {
            text-align: center !important;
            font-size: 12px !important;
        }

        .el-butto {
            width: 50px !important;
            padding: 0 !important;
        }

        .el-button.is-text {
            padding: 9px 0 !important;
        }

        .el-button>span {
            color: #17b3a3 !important;
            font-size: 12px;
        }
    }

    :deep .dialog {
        .el-table thead th {
            background-color: #fff !important;
            color: #909399;
        }

        .cell {
            text-align: center !important;
            font-size: 12px !important;
        }
    }
}
</style>